package com.kaibes.platform.file.client.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.orm.core.listener.DeleteListener;
import com.kaibes.orm.curd.Delete;
import com.kaibes.orm.spring.OrmListener;
import com.kaibes.platform.file.client.db.FileMap;
import com.kaibes.platform.file.client.db.FileMapService;
import com.kaibes.platform.file.client.db.FileServer;
import com.kaibes.platform.file.client.db.FileServerService;
import com.kaibes.platform.file.client.token.FileTokenUtils;
import com.kaibes.web.base.HttpMethodOverrideConsts;

@OrmListener(service = FileMapService.class)
public class FileMapDeleteListener implements DeleteListener {

    @Autowired
    private FileMapService fileMapService;
    @Autowired
    private FileServerService fileServerService;
    @Autowired
    private FileTokenUtils fileTokenUtils;
    @Autowired
    private RestTemplate restTemplate;

    private ThreadLocal<List<FileMap>> threadLocal = new ThreadLocal<>();

    @Override
    public void beforeDelete(Delete delete) throws Exception {
        List<FileMap> fileMaps = fileMapService.list(delete.getQueries());
        if (!fileMaps.isEmpty()) {
            threadLocal.set(fileMaps);
        }
    }

    @Override
    public void afterDelete(Delete delete, int count) throws Exception {
    	List<FileMap> list = threadLocal.get();
    	Map<Integer, List<String>> map = new HashMap<>();
    	// 分组
    	for (Iterator<FileMap> iterator = list.iterator(); iterator.hasNext();) {
			FileMap fileMap = iterator.next();
			List<String> temp = map.get(fileMap.getServerId());
			if (temp == null) {
				temp = new ArrayList<>();
				map.put(fileMap.getServerId(), temp);
			}
			temp.add(fileMap.getUuid());
		}
    	// 遍历所有的组
    	Set<Entry<Integer, List<String>>> entrySet = map.entrySet();
    	for (Entry<Integer, List<String>> entry : entrySet) {
    		// 获取对应组的服务器信息
    		FileServer fileServer = fileServerService.getById(entry.getKey());
    		if (fileServer != null) {
    			// 够造请求
        		final String listString = fileTokenUtils.writeListString(fileServer, entry.getValue());
        		final String url = fileServer.getHost() + "/encrypts/files/" + fileServer.getUserId();
        		HashMap<String, String> data = new HashMap<>();
        		data.put("uuids", listString);
        		// 发送删除请求到服务器
        		delete(url, data);
    		}
		}
    }
    
    @Autowired
    private ObjectMapper objectMapper;
    
    public void delete(String url, Map<String, String> data) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(HttpMethodOverrideConsts.DEFAULT_HEADER_PARAM, HttpMethod.DELETE.name());
        try {
            String value = objectMapper.writeValueAsString(data);
            HttpEntity<String> requestEntity = new HttpEntity<>(value, headers);
            restTemplate.postForEntity(url, requestEntity, String.class);
        } catch (Exception e) {
        }
        
    }
    
}
